package com.daidai.activitys

import android.app.ActivityManager
import android.content.Context
import android.graphics.PixelFormat
import android.os.Process
import android.view.WindowManager
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import com.daidai.base.BaseActivity
import com.daidai.spinner.R
import com.daidai.tools.MyLog
import com.worker.TestWorker
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.lang.Exception


class VM:ViewModel(){
    fun  delayRun(timems:Long,action:()->Unit){
        viewModelScope.launch {
            delay(timems)
            action.invoke()
        }
    }
}

class WindowActivity: BaseActivity() {

    val model : VM by viewModels()
    override fun getContentViewResId(): Int = R.layout.activity_window

    override fun initView() {
        findBtn(R.id.btnWindow).setOnClickListener {
           //  showWindow()
            val request = OneTimeWorkRequestBuilder<TestWorker>().build()
            WorkManager.getInstance(this).enqueue(request)

        }

        MyLog.info("pid:${Process.myPid()}")
        MyLog.info("myUserId:${Process.myUid()}")
        MyLog.info("uid:${Process.myUserHandle().toString()}")

//        forceStopPackage("com.example.firstcompose",this)

        findBtn(R.id.btnToast).setOnClickListener {
            model.delayRun(0){
                MyLog.info("显示出来.....................")
                val toast = Toast(this)
                val view = layoutInflater.inflate(R.layout.toast_ad,null)
                val clz = Class.forName("android.widget.Toast")
                val nextViewField = clz.getDeclaredField("mNextView")
                val durationField  = clz.getDeclaredField("mDuration")

                nextViewField.isAccessible = true
                nextViewField.set(toast,view)
                durationField.isAccessible = true
                durationField.set(toast,1)

                val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
                val amClz = Class.forName("android.app.ActivityManager")
                // getService
                val methods = amClz.getDeclaredMethods()

                MyLog.info("===============================")
                for (m in methods){
                    MyLog.info("m.name:${m.name}")
                }
                MyLog.info("===============================")

//                MyLog.info("methods:${methods}")
//                if (serviceMethod != null){
//                    MyLog.info("serviceMethod is not null!")
//                }else{
//                    MyLog.info("serviceMethod is  null!")
//                }

                //val pwmClz = Class.forName("com.android.server.policy.PhoneWindowManager")
                toast.show()
            }
        }

    }

    override fun initData() {
    }

    private fun showWindow(){
        val winMgr = getSystemService(WINDOW_SERVICE) as WindowManager
        val params = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_APPLICATION,
            0,
            PixelFormat.TRANSPARENT
        )
        params.title = "TestWindow"
        val rootView = layoutInflater.inflate(R.layout.root_view, null)
        winMgr.addView(rootView, params)
    }

    /**
     * 强制停止应用程序
     * @param pkgName
     */
    private fun forceStopPackage(pkgName: String, context: Context) {
        MyLog.info("forceStopPackage ${pkgName} start!")
        try {
            val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val clz = Class.forName("android.app.ActivityManager")
            val methods  = clz.methods
            val method = methods.find { it.name == "forceStopPackage" }
            if (method != null){
                MyLog.info("method is not null!")
                method.isAccessible = true
            }else{
                MyLog.info("method is  null!")
            }

//            val fileds = clz.fields
//            val filed = fileds.find { it-> it.name == "mContext" }
//            if (filed != null){
//                filed.isAccessible = true
//                val refContext = filed.get(am)
//                MyLog.info("refContext:${refContext}")
//                MyLog.info("baseContext:${baseContext}")
//                MyLog.info("is the same context : ${baseContext == refContext}")
//            }else{
//                MyLog.info("filed is null!")
//            }
//            val method: Method = Class.forName("android.app.ActivityManager").getMethod(
//                "forceStopPackage",
//                String::class.java
//            )
//            method.invoke(am, pkgName)
//            MyLog.info("强制杀掉应用:${pkgName}成功!")
        }catch (e:Exception){
            MyLog.info("msg:${e.message}")
            MyLog.info("强制杀掉应用:${pkgName}失败!")
        }
    }

}